package com.zaoniao.enstudy.domain.service;

import com.zaoniao.enstudy.api.dto.VocabularyAddDto;
import com.zaoniao.enstudy.api.dto.VocabularyDelDto;
import com.zaoniao.enstudy.api.dto.VocabularyUpdDto;
import com.zaoniao.enstudy.domain.entity.Vocabulary;
import com.zaoniao.enstudy.domain.repository.UserVocabularyRepository;
import com.zaoniao.enstudy.domain.repository.UserVocabularyWordsRepository;
import com.zaoniao.enstudy.infracore.exception.AppException;
import com.zaoniao.enstudy.infracore.web.CommonError;
import com.zaoniao.enstudy.infracore.web.PagedGridResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VocabularyService {

    /**
     * 用户词汇表仓储层业务注入.
     */
    private final UserVocabularyRepository userVocabularyRepository;

    /**
     * 用户词汇表明细仓储层业务注入.
     */
    private final UserVocabularyWordsRepository vocabularyWordsRepository;

    /**
     * 新增词汇表
     *
     * @param vocabularyDto 新增-词汇表入参对象
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addUserVocabulary(VocabularyAddDto vocabularyDto) {
        if (!userVocabularyRepository.checkName(VocabularyAddDto.Converter.INSTANCE.dto2do(vocabularyDto))) {
            // 不存在，新增
            userVocabularyRepository.insert(VocabularyAddDto.Converter.INSTANCE.dto2do(vocabularyDto));
        } else {
            // 存在即抛出业务异常
            throw new AppException(CommonError.BusinessError, "当前用户已经存在相同名称的词汇表！");
        }
    }

    /**
     * 修改词汇表
     *
     * @param vocabularyDto 修改-词汇表入参对象
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updUserVocabulary(VocabularyUpdDto vocabularyDto) {
        userVocabularyRepository.updUserVocabulary(vocabularyDto.getVocabularyId(), vocabularyDto.getVocabularyName());
    }

    /**
     * 删除词汇表
     *
     * @param vocabularyDto 删除-词汇表入参对象
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void delUserVocabulary(VocabularyDelDto vocabularyDto) {
        userVocabularyRepository.delUserVocabulary(vocabularyDto.getVocabularyId());
        vocabularyWordsRepository.updStatusByVocabularyId(vocabularyDto.getVocabularyId());
    }

    /**
     * 词汇表分页查询.
     *
     * @param userId 用户id
     * @param page   第几页
     * @param size   每页显示数量
     * @return 词汇表列表
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public PagedGridResult<Vocabulary> getVocabularyPage(String userId, Integer page, Integer size) {
        return userVocabularyRepository.getVocabularyPage(userId, page, size);
    }
}
